package com.spring.applicationEven_annotation_demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 使用@Async 注解必须在Configuration添加@EnableAsync ，并且要添加TaskExecutor配置。
 *
 * @EventListener注解原理  SmartInitializingSingleton接口、以及ioc初始化的AbstractApplicationContext#refresh().finishBeanFactoryInitialization
 *
 */
@Configuration
@EnableAsync
public class Config {

	@Bean(name="processExecutor")
	public TaskExecutor workExecutor() {
		ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
		threadPoolTaskExecutor.setThreadNamePrefix("Async-");
		threadPoolTaskExecutor.setCorePoolSize(10);
		threadPoolTaskExecutor.setMaxPoolSize(20);
		threadPoolTaskExecutor.setQueueCapacity(600);
		threadPoolTaskExecutor.afterPropertiesSet();

		// 自定义拒绝策略
		threadPoolTaskExecutor.setRejectedExecutionHandler((r, executor) -> {
			// .....
		});
		// 使用预设的拒绝策略
		threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
		return threadPoolTaskExecutor;
	}

	@Bean
	public BlackListNotifier blackListNotifier(){
		BlackListNotifier blackListNotifier = new BlackListNotifier();
		blackListNotifier.setNotificationAddress("abcd@126.com");
		return blackListNotifier;
	}

	@Bean
	public EmailService emailService(){
		EmailService emailService = new EmailService();
		List<String> list = new ArrayList<>();
		list.add("qqq@qq.com");
		list.add("123@qq.com");
		list.add("456@qq.com");
		emailService.setBlackList(list);
		return emailService;
	}
}
